<?php
namespace app\common\util;

/**
 * Class Srt 两种字幕格式的字幕提取
 */
class Srt {

    /**
     * 返回的数据结构
     * [
     * [
        en:'',
     *  cn:'',
     *  start_minute:'',
     *  start_second:'',
     *  end_minute:'',
     *  end_second:'',
     * ],[]
     * ]
     * //type  1 只有英文 2 只有中文  3英中双语  4中英双语
     */
    public static function parseSrt($filePath,$type = 1){
        $content = file_get_contents($filePath);
        $regex = "/(?:\d{2}:\d{2}:\d{2}\,\d+)\s*-->\s*(?:\d{2}:\d{2}:\d{2}\,\d+)(?:[\s\S]+?)\r\n\r\n/";
        $res = preg_match_all($regex,$content,$matches);
        $result = [];
        if($res){
            foreach($matches[0] as $key => $val ){
               $item = explode("\r\n",$val);
               $time = $item[0];
               $firstLang = trim($item[1]);
               $secondLang = trim($item[2]);
               if($type == 1 || $type == 3){
                   $en = $firstLang;
                   $cn = $secondLang;
               }else{
                   $en = $secondLang;
                   $cn = $firstLang;
               }
               $time = self::parseTimeRegion($time);
               $startTime = self::parseTime($time[0]);
               $endTime = self::parseTime($time[1]);
                array_push($result,[
                    'en'=>$en,
                    'cn'=>$cn,
                    'start_second'=>$startTime[0],
                    'start_millisecond'=>$startTime[1],
                    'end_second'=>$endTime[0],
                    'end_millisecond'=>$endTime[1],
                    'start'=>$time[0],
                    'end'=>$time[1]
                ]);
            }
        }

        return $result;
    }

    private static function parseTimeRegion($time){
        $timeArr = explode("-->",$time);
        $start = trim($timeArr[0]);
        $end = trim($timeArr[1]);
        return [$start,$end];
    }

    private static function parseTime($time){
        $timeArr = explode(",",$time);
        $font = trim($timeArr[0]);
        $millisecond = intval(trim($timeArr[1])) * 0.001;
        $font = explode(":",$font);
        $second = intval($font[0]) * 3600 + intval($font[1]) * 60 + intval($font[2]);
        return [$second,$millisecond];
    }

    /**
     *
     */
    public static function parseVtt($filePath){

    }

}